<template>
  <div>
    <div class="card" style="margin-bottom: 5px">
        <el-input
            v-model="data.searchName"
            prefix-icon="el-icon-search"
            style="width: 240px; margin-right: 10px"
            placeholder="请输入学生姓名查询"
            @keyup.enter="load"
        ></el-input>
        <el-select v-model="data.selectedClassId" placeholder="请选择班级" style="width: 180px; margin-right: 10px">
          <el-option value="" label="全部班级"></el-option>
          <el-option v-for="item in data.classList" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
        <el-button type="info" plain @click="load">查询</el-button>
        <el-button type="warning" plain style="margin: 0 10px" @click="reset">重置</el-button>
    </div>
      <!-- 表格和其他代码... -->
    <div class="card" style="margin-bottom: 5px">

      <el-table
          stripe
          :data="data.tableData"
          :row-key="row => row.id"
          @expand-change="handleExpand"
          style="width: 100%"
      >
        <!-- 主表格列 -->
        <el-table-column prop="name" label="学生姓名" class-name="custom-header" />
        <el-table-column prop="username" label="学号" class-name="custom-header" />
        <el-table-column prop="className" label="班级" class-name="custom-header" />

        <!-- 展开列 -->
        <el-table-column type="expand">
          <template v-slot="props">
            <div>
              <!-- 子列表的数据绑定到当前行的 expandedData -->
              <el-table
                  :data="props.row.expandedData"
                  :row-key="subItem => subItem.id"
                  style="width: 100%"
              >
                <!-- 展开行数据列 -->
                <el-table-column prop="metricsName" label="指标名称" />
                <el-table-column label="描述">
                  <template v-slot="scope">
                    <span v-if="scope.row.description">{{ scope.row.description }}</span>
                    <span v-else>无</span>
                  </template>
                </el-table-column>                <el-table-column label="得分" width="180">
                  <template v-slot="scope">
                    <div style="display: flex; align-items: center;">
                      <el-input v-model="scope.row.score" size="mini" style="width: 100px;"></el-input>
                      <el-button
                          size="mini"
                          type="primary"
                          @click="updateScore(scope.row)"
                          style="margin-left: 10px;"
                      >
                        提交
                      </el-button>
                    </div>
                  </template>
                </el-table-column>
<!--                <el-table-column prop="status" label="状态" />-->
                <el-table-column prop="status" label="状态">
                  <template v-slot="scope">
                    <span v-if="scope.row.status === '已审批'" class="approved">{{ scope.row.status }}</span>
                    <span v-else-if="scope.row.status" class="highlight">{{ scope.row.status }}</span>
                    <span v-else class="highlight">未提交</span>
                  </template>
                </el-table-column>
                <el-table-column label="附件" width="150">
                  <template v-slot="scope">
                    <!-- 显示附件链接 -->
                    <a v-if="scope.row.attachment" :href="scope.row.attachment" target="_blank">下载附件</a>
                    <a v-else>无</a>
                  </template>
                </el-table-column>
                <el-table-column prop="submitTime" label="提交时间" />
              </el-table>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup>
import { reactive, onMounted } from 'vue';
import request from "@/utils/request.js";
import { ElMessage } from "element-plus";

const data = reactive({
  tableData: [],
  pageNum: 1,
  pageSize: 10,
  total: 0,
  searchName: null, // 添加搜索关键字属性
  classList: [],
  selectedClassId: "", // 添加用于筛选的班级 ID
});
request.get('/classInfo/selectAll').then(res => { data.classList = res.data })

// 加载主列表数据
const load = () => {
  request
      .get("/submit/stulist", {
        params: {
          name: data.searchName,
          pageNum: data.pageNum,
          pageSize: data.pageSize,
          classId: data.selectedClassId
        },
      })
      .then((res) => {
        if (res.code === '200') {
          data.tableData = res.data?.list || [];
          data.total = res.data?.total;
        }
      });
};

// 加载子列表数据
const loadIndependentSubListData = (row) => {
  request
      .get("/submit/selectAll", {
        params: { studentId: row.id } // 假设子列表数据需要父列表项的 ID
      })
      .then((res) => {
        if (res.code === '200') {
          row.expandedData = res.data || []; // 将加载的数据赋值给当前行的 expandedData
        }
      })
      .catch((err) => {
        ElMessage.error("子列表数据加载失败");
      });
};

// 处理行展开事件
const handleExpand = (row, expandedRows) => {
  if (expandedRows.includes(row) && !row.expandedData?.length) {
    loadIndependentSubListData(row);
  }
};
// 更新得分
const updateScore = async (row) => {
  try {
    // 第一步：更新得分
    const updateResponse = await request.put("/submit/update", {
      id: row.id,
      score: row.score,
      status: "已审批",
    });

    if (updateResponse.code === '200') {
      ElMessage.success("得分更新成功");

      // 第二步：获取 stuAll 数据
      const stuAllResponse = await request.get("/submit/stuUpdate", {
        params: { id: row.studentId },
      });
      console.log(stuAllResponse.data)
      if (stuAllResponse.code === '200') {
        // 第三步：更新 student 数据
        const studentUpdateResponse = await request.put("/student/update", {
          id: stuAllResponse.data.id,
          extra: stuAllResponse.data.extra,
        });

        if (studentUpdateResponse.code === '200') {
          ElMessage.success("指标得分更新成功");

          // 更新受影响的行
          loadIndependentData(row.id);
        } else {
          ElMessage.error("指标得分更新失败");
        }
      } else {
        ElMessage.error("获取指标数据失败");
      }
    } else {
      ElMessage.error("得分更新失败");
    }
  } catch (error) {
    ElMessage.error("操作失败，请稍后再试");
    console.error("请求失败：", error);
  }
};


// 加载特定行的数据
const loadIndependentData = (id) => {
  request.get(`/submit/selectById/${id}`)
      .then((res) => {
        if (res.code === '200' && res.data) {
          const index = data.tableData.findIndex(item => item.id === id);
          if (index !== -1) {
            // 更新特定行的数据
            data.tableData[index] = res.data;
          }
        } else {
          ElMessage.error("行数据加载失败");
        }
      })
      .catch((err) => {
        ElMessage.error("行数据加载失败");
      });
};
const reset = () => {
  data.searchName = ""
  data.selectedClassId = ""
  load();
};
;
onMounted(() => {
  load();
});
</script>
<style>
.approved {
  border: 1px solid green; /* 绿色边框 */
  color: green; /* 绿色文本 */
  padding: 2px 4px; /* 内边距 */
}
.highlight {
  border: 1px solid red; /* 红框 */
  color: red; /* 红色文本 */
  padding: 2px 4px; /* 内边距 */
}
.pending {
  border: 1px solid yellow; /* 黄色边框 */
  color: yellow; /* 黄色文本 */
  padding: 2px 4px; /* 内边距 */
}
</style>